package com.reservation.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String region;


    /**
     * 文件上传
     *
     * @param content 文件字节数组
     * @param originalFilename 原始文件名
     * @return 访问URL
     */
    public String upload(byte[] content, String originalFilename) {
        // 生成按日期分类的目录结构
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));

        // 生成随机文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = dir + "/" + UUID.randomUUID() + extension;

        // 配置OSS客户端
        ClientBuilderConfiguration clientConfig = new ClientBuilderConfiguration();
        clientConfig.setSignatureVersion(SignVersion.V4);

        // 创建OSS实例
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .region(region)
                .credentialsProvider(new DefaultCredentialProvider(accessKeyId, accessKeySecret))
                .clientConfiguration(clientConfig)
                .build();

        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));

            // 构建文件访问URL
            String fileUrl = "https://" + bucketName + "." + endpoint + "/" + objectName;
            log.info("文件上传成功，访问路径: {}", fileUrl);
            return fileUrl;
        } catch (OSSException oe) {
            log.error("OSS服务端异常: {} - {} - {} - {}",
                    oe.getErrorCode(), oe.getErrorMessage(), oe.getRequestId(), oe.getHostId());
            throw oe;
        } catch (ClientException ce) {
            log.error("OSS客户端异常: {}", ce.getMessage());
            throw ce;
        } finally {
            ossClient.shutdown();
        }
    }


}

